//
//  PrepareViewController.m
//  WisdomLive
//
//  Created by UserLcc on 2018/5/10.
//  Copyright © 2018年 com.jszhaomi. All rights reserved.
//

#import "PrepareViewController.h"
#import "BarButtonView.h"
#import "Masonry.h"
#import "UILabel+YBAttributeTextTapAction.h"
#import "MediaCaptureViewController.h"
#import "NEMediaCaptureEntity.h"
#import "WSHttpManager.h"
#import "LoginViewController.h"
#import "BaseRuleVC.h"
@interface PrepareViewController ()<YBAttributeTapActionDelegate>
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *descLabel;

@end

@implementation PrepareViewController
{
    UIButton *enterBtn;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [WSHttpManager neteaseliveInfoComplete:^(DCHttpResult result, NSString *errorMessage, id responseData) {
        if (result) {
            NSDictionary *tmp = [responseData objectForKey:@"data"];
            self.nameLabel.text = [NSString stringWithFormat:@"%@",[tmp objectForKey:@"name"]];
            self.descLabel.text = [NSString stringWithFormat:@"%@",[tmp objectForKey:@"description"]];
            [[NSUserDefaults standardUserDefaults] setValue:[tmp objectForKey:@"pushUrl"] forKey:@"streamURL"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            enterBtn.enabled = YES;
        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self changeNaviColor:[UIColor colorWithRed:11/255.f green:159/255.f blue:1 alpha:1]];
    
    self.title = @"书房Live";
    
//    [self addLeftBtn];
    [self addRightBtn];
    
    UIImageView *bacImage = [UIImageView new];
    bacImage.contentMode = UIViewContentModeScaleAspectFill;
    bacImage.image = [UIImage imageNamed:@"Bg-1"];
    [self.view addSubview:bacImage];
    [bacImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mas_topLayoutGuideBottom);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
    
    
    self.nameLabel = [UILabel new];
    self.nameLabel.font = [UIFont systemFontOfSize:24];
    self.nameLabel.textColor = [UIColor whiteColor];
    self.nameLabel.backgroundColor = [UIColor clearColor];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.nameLabel];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).mas_offset(20);
        make.right.mas_equalTo(self.view).mas_offset(-20);
        make.top.mas_equalTo(self.mas_topLayoutGuideBottom).mas_offset(40);
    }];
    
    self.descLabel = [UILabel new];
    self.descLabel.font = [UIFont systemFontOfSize:15];
    self.descLabel.textColor = [UIColor whiteColor];
    self.descLabel.backgroundColor = [UIColor clearColor];
    self.descLabel.textAlignment = NSTextAlignmentCenter;
    self.descLabel.text = @"开启你的知识分享之旅";
    [self.view addSubview:self.descLabel];
    [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).mas_offset(20);
        make.right.mas_equalTo(self.view).mas_offset(-20);
        make.top.mas_equalTo(self.mas_topLayoutGuideBottom).mas_offset(75);
    }];
    
    UIImageView *image_left = [UIImageView new];
    UIImageView *image_center = [UIImageView new];
    UIImageView *image_right = [UIImageView new];
    
    image_left.contentMode =
    image_center.contentMode =
    image_right.contentMode = UIViewContentModeScaleAspectFill;
    
    image_left.backgroundColor =
    image_center.backgroundColor =
    image_right.backgroundColor = [UIColor clearColor];
    
    image_left.image = [UIImage imageNamed:@"ic_dianchi"];
    image_center.image = [UIImage imageNamed:@"ic_wifi"];
    image_right.image = [UIImage imageNamed:@"ic_light"];
    
    [self.view addSubview:image_left];
    [self.view addSubview:image_center];
    [self.view addSubview:image_right];
    
    [image_center mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 70));
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.descLabel.mas_bottom).mas_offset(145*ratio);
    }];
    
    [image_left mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 70));
        make.top.mas_equalTo(self.descLabel.mas_bottom).mas_offset(145*ratio);
        make.right.mas_equalTo(image_center.mas_left).mas_offset(-40*ratio);
    }];
    
    [image_right mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 70));
        make.top.mas_equalTo(self.descLabel.mas_bottom).mas_offset(145*ratio);
        make.left.mas_equalTo(image_center.mas_right).mas_offset(40*ratio);
    }];
    
    UILabel *tipsLabel = [UILabel new];
    tipsLabel.font = [UIFont systemFontOfSize:15*ratio];
    tipsLabel.textColor = [UIColor whiteColor];
    tipsLabel.backgroundColor = [UIColor clearColor];
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    tipsLabel.numberOfLines = 0;
    tipsLabel.text = @"请您保证手机电量充足，\n网络通畅，\n灯光不要太暗哦，\n祝您直播愉快哦！";
    [self.view addSubview:tipsLabel];
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).mas_offset(20);
        make.right.mas_equalTo(self.view).mas_offset(-20);
        make.top.mas_equalTo(image_center.mas_bottom).mas_offset(25*ratio);
    }];
    
    
    UILabel *label_bottom = [UILabel new];
    label_bottom.backgroundColor = [UIColor clearColor];
    NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc] initWithString:@"直播即为同意《智慧书房用户直播协议》"];
    [attstr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, 6)];
    [attstr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:11/255.f green:159/255.f blue:1 alpha:1] range:NSMakeRange(6, attstr.length-6)];
    [attstr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, attstr.length)];
    label_bottom.attributedText = attstr;
    [label_bottom yb_addAttributeTapActionWithStrings:@[@"《智慧书房用户直播协议》"] delegate:self];
    [self.view addSubview:label_bottom];
    [label_bottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).mas_offset(-62*ratio);
    }];
    
    
    enterBtn = [UIButton new];
    enterBtn.enabled = NO;
    enterBtn.backgroundColor = [UIColor colorWithRed:11/255.f green:159/255.f blue:1 alpha:1];
    enterBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [enterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    enterBtn.layer.cornerRadius = 6.f;
    [enterBtn setTitle:@"进入直播间" forState:UIControlStateNormal];
    [enterBtn addTarget:self action:@selector(enterBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:enterBtn];
    [enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(label_bottom.mas_top).mas_offset(-13);
        make.left.mas_equalTo(self.view).mas_offset(40);
        make.right.mas_equalTo(self.view).mas_offset(-40);
        make.height.mas_equalTo(44);
    }];
}


-(void)leftBtnAction{
    
}

-(void)rightBtnAction{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确认退出" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [WSHttpManager logOut:^(DCHttpResult result, NSString *errorMessage, id responseData) {
            if (result) {
                [[NSUserDefaults standardUserDefaults]  setValue:@"" forKey:@"userName"];
                [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"password"];
                [UIApplication sharedApplication].keyWindow.rootViewController = [LoginViewController new];
            }
        }];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
    
    
}

-(void)enterBtnAction{
    
    LSVideoParaCtxConfiguration *config = [LSVideoParaCtxConfiguration defaultVideoConfiguration:LSVideoParamQuality_Super];
    config.fps = 20;
    config.cameraPosition = LS_CAMERA_POSITION_FRONT;
    config.isCameraZoomPinchGestureOn = YES;
    config.isFrontCameraMirroredPreView = YES;
    config.isVideoFilterOn = YES;
    config.filterType = LS_GPUIMAGE_ZIRAN;
    config.isVideoWaterMarkEnabled = NO;
    config.interfaceOrientation = LS_CAMERA_ORIENTATION_PORTRAIT;
    [NEMediaCaptureEntity sharedInstance].videoParaCtx = config;
    
    MediaCaptureViewController *mediaCaptureVC = [[MediaCaptureViewController alloc] initWithUrl:[[NSUserDefaults standardUserDefaults] valueForKey:@"streamURL"] sLSctx:[NEMediaCaptureEntity sharedInstance].videoParaCtx];
    [self presentViewController:mediaCaptureVC animated:YES completion:nil];
}


-(void)yb_attributeTapReturnString:(NSString *)string range:(NSRange)range index:(NSInteger)index{
    BaseRuleVC *vc = [[BaseRuleVC alloc] init];
    vc.code = @"A022";
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:navi animated:YES completion:nil];
}


////////////////**********TOOLS***********////////////////

-(void)addLeftBtn{
    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 34, 30)];
    [btn setImage:[UIImage imageNamed:@"ic_sao"] forState:UIControlStateNormal];
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 11)
    {
        BarButtonView *barBtnView = [[BarButtonView alloc] initWithFrame:btn.frame];
        [barBtnView setPosition:BarButtonViewPositionLeft];
        [barBtnView addSubview:btn];
        [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:barBtnView]];
    }
    else
    {
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL];
        [space setWidth:-10];
        [self.navigationItem setLeftBarButtonItems:@[space,[[UIBarButtonItem alloc] initWithCustomView:btn]]];
    }
    [btn addTarget:self action:@selector(leftBtnAction) forControlEvents:UIControlEventTouchUpInside];
}

-(void)addRightBtn{
    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [btn setTitle:@"退出" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    //使右侧按钮往右移动
    [btn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 11)
    {
        BarButtonView *barBtnView = [[BarButtonView alloc] initWithFrame:btn.frame];
        [barBtnView setPosition:BarButtonViewPositionRight];
        [barBtnView addSubview:btn];
        [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:barBtnView]];
    }
    else
    {
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL];
        [space setWidth:-10];
        [self.navigationItem setRightBarButtonItems:@[space,[[UIBarButtonItem alloc] initWithCustomView:btn]]];
    }
}

-(void)changeNaviColor:(UIColor *)color{
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:18],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    //self.navigationController.navigationBar.barStyle=UIStatusBarStyleLightContent;
    //self.navigationController.navigationBar.barTintColor=color;
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:color]
                                                 forBarPosition:UIBarPositionAny
                                                     barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
